package com.atguigu.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName MyLB
 * @Description 模仿源码IRule手写轮询算法
 * @Author 周轩霆
 * @Date 2022/10/17 20:40
 **/
@Component
public class MyLB implements LoadBalancer {
    //原子类 成员变量 CAS+自旋锁 默认是0
    private AtomicInteger atomicInteger = new AtomicInteger();

    //求 当前是第几次访问
    public final int getAndIncrement() {
        int current, next;
        do {
            //默认是0
            current = this.atomicInteger.get();
            //int maxValue = Integer.MAX_VALUE;2147483647
            next = current >= 2147483647 ? 0 : current + 1;
        } while (!this.atomicInteger.compareAndSet(current, next));
        //自旋锁 比较并交换 VAB 多线程环境下。。。JUC
        System.out.println("*****第几次访问，次数next: " + next);
        return next;
    }

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        //轮询算法的核心
        int index = getAndIncrement() % serviceInstances.size();
        //返回的是哪一个具体的服务
        return serviceInstances.get(index);
    }
}
